﻿using System;
using System.Linq;
using StreetPacMan.Server.Facade;

namespace StreetPacMan.Server.Rules.PlayerLocationChangeRules
{
    public class StartGameByPacManRule : IHandlePlayerLocationChangedRule
    {
        public void Handle(PacManDataContext dataContext, ServerPollParameters serverPollParameters, ref bool shouldContinueHandling)
        {
            if(serverPollParameters.IsEnabled==false)
            {
                return;
            }

            var player = dataContext.Players.Where(x=>x.Id==serverPollParameters.EntityId).Single();
            if(player.RoleEnum!=PlayerRole.PacMan)
            {
                return;
            }

            var game = player.Game;
            if (game.StateEnum != GameState.WatingForNextPacManToStart &&
                game.StateEnum != GameState.WaitingForMorePlayersToJoin)
            {
                return;
            }

            game.StateEnum = GameState.Started;
            game.StateChangeTime = DateTime.Now;
            dataContext.AddGameEvent(EventType.GameStateIsNormalPacMan, player.Name + " started the game", player.Id, player.GameId);
        }
    }
}